#pragma once

#include <iostream>
using namespace std;
#include <string>
#include <cstring>
#include <queue>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class Task
{
public:
    Task()
    {
    }

    Task(int sock,sockaddr_in* ppeer)
        : _sock(sock)
        ,_ppeer(ppeer)
    {
    }

    void run()
    {
        while (true)
        {
            char buffer[1024] = {0};
            ssize_t s = read(_sock, buffer, sizeof(buffer) - 1);
            if (s > 0)
            {
                // s-1位置是回车，用0 覆盖做结尾
                //  char* inet_ntoa(struct in_addr in);函数把网络序列ip转为主机序列字符串形式ip
                string client_ip = inet_ntoa(_ppeer->sin_addr);
                uint16_t client_port = ntohs(_ppeer->sin_port);
                buffer[s - 1] = 0;
                cout << "client[" << client_ip << ":"<< client_port << "]:>"<< buffer << endl;
                // 服务器返回信息
                write(_sock, buffer, strlen(buffer));
            }
            else if (s == 0)
            {
                cout << "client quit......" << endl;
                // 任务完成，关闭描述符
                close(_sock);
                break;
            }
            else
            {
                cerr << "read error" << endl;
            }
        }
    }

    ~Task()
    {
    }

private:
    int _sock;
    sockaddr_in* _ppeer;
};